#include "seqiot.h"
#include "model.h"
#include "sqlite.h"

#define SQL_PRODUCT_COLS "id,name,protocol,vendor,model,lua_u0,lua_i0,lua_ubb,lua_ibb,lua_u_decimal,lua_i_decimal,lua_p_decimal,is_shift,di_shift,do_shift,ai_shift,ao_shift,product_key,product_secret"

product_t *product_new() {
    return z_calloc(1, sizeof(product_t));
}

void product_free(product_t *product) {
    if (!product)return;

    for (int i = 0; i < sizeof(product->thing_model) / sizeof(product->thing_model[0]); ++i) {
        vector_t *tag_list = &product->thing_model[i];
        vector_foreach(tag_list, (vector_foreach_callback) thing_model_free);
        vector_clear(tag_list);
    }

    z_free(product);
}

void read_row_product(sqlite3_stmt *stmt, product_t *rs) {
    int idx = 2;
    read_row_object(stmt, &rs->super);

    rs->protocol = sqlite3_column_int(stmt, idx++);

    read_row_str(stmt, idx++, rs->vendor, sizeof(rs->vendor));
    read_row_str(stmt, idx++, rs->model, sizeof(rs->model));

    read_row_str(stmt, idx++, rs->u0, sizeof(rs->u0));
    read_row_str(stmt, idx++, rs->i0, sizeof(rs->i0));
    read_row_str(stmt, idx++, rs->ubb, sizeof(rs->ubb));
    read_row_str(stmt, idx++, rs->ibb, sizeof(rs->ibb));
    read_row_str(stmt, idx++, rs->u_decimal, sizeof(rs->u_decimal));
    read_row_str(stmt, idx++, rs->i_decimal, sizeof(rs->i_decimal));
    read_row_str(stmt, idx++, rs->p_decimal, sizeof(rs->p_decimal));
    rs->is_shift = sqlite3_column_int(stmt, idx++);
    rs->di_shift = sqlite3_column_int(stmt, idx++);
    rs->do_shift = sqlite3_column_int(stmt, idx++);
    rs->ai_shift = sqlite3_column_int(stmt, idx++);
    rs->ao_shift = sqlite3_column_int(stmt, idx++);

    read_row_str(stmt, idx++, rs->product_key, sizeof(rs->product_key));
    read_row_str(stmt, idx++, rs->product_secret, sizeof(rs->product_secret));
}

int read_stmt_products(sqlite3 *db, vector_t *products) {
    int rc = -1;
    sqlite3_stmt *stmt = NULL;
    char sql[1024];

    sprintf(sql, "SELECT %s FROM product WHERE %s", SQL_PRODUCT_COLS, SQL_DISABLE);
    rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
    if (SQLITE_OK != rc) {
        sqlite_check(db);
        goto err;
    }

    while (SQLITE_ROW == sqlite3_step(stmt)) {
        product_t *product = product_new();
        read_row_product(stmt, product);
        vector_add(products, product);
    }

    err:
    sqlite3_finalize(stmt);
    return rc;
}